package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.domain.db.UserInfo;
import com.itheima.mapper.UserInfoMapper;
import com.itheima.service.db.UserInfoService;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.testSoulVo.SimilarYouVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    // 更新用户信息
    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    // 查询用户信息
    @Override
    public UserInfo findById(Long userId) {
        return userInfoMapper.selectById(userId);
    }

    // 分页查询
    @Override
    public PageBeanVo findByPage(Integer pageNum, Integer pageSize) {
        // 构建分页对象
        Page<UserInfo> page = new Page<>(pageNum, pageSize);
        // 分页查询
        page = userInfoMapper.selectPage(page, null);
        // 封装vo并返回
        return new PageBeanVo(pageNum, pageSize, page.getTotal(), page.getRecords());
    }

    //用户解冻
    @Override
    public void saveFreeze(int userId) {
        userInfoMapper.updateFreeze(Long.valueOf(userId));
    }

    //用户冻结
    @Override
    public void updateFreeze(int userId) {
        userInfoMapper.updateUnfreeze(Long.valueOf(userId));
    }

    //通过userIds进行查找用户信息
    @Override
    public List<SimilarYouVo> findByIdsVo(List<Long> userIds, Long id) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("id",userIds);
        wrapper.ne("id",id);
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        List<SimilarYouVo> vos = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            SimilarYouVo vo = SimilarYouVo.inint(userInfo);
            vos.add(vo);
        }
        return vos;
    }

    //根据id集合批量查询
    @Override
    public Map<Long, UserInfo> findByIds(List<Long> userIdList) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CollUtil.isNotEmpty(userIdList), UserInfo::getId, userIdList);
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        Map<Long, UserInfo> map = new HashMap<>();
        for (UserInfo userInfo : userInfos) {
            map.put(userInfo.getId(), userInfo);
        }
        return map;
    }
}
